package com.gbs.flash.api.controller.shop;

import com.gbs.flash.bean.constant.factory.PageFactory;
import com.gbs.flash.bean.core.BussinessLog;
import com.gbs.flash.bean.entity.shop.AttrKey;
import com.gbs.flash.bean.exception.ApplicationException;
import com.gbs.flash.bean.exception.ApplicationExceptionEnum;
import com.gbs.flash.bean.vo.front.Rets;
import com.gbs.flash.service.shop.AttrKeyService;
import com.gbs.flash.utils.StringUtil;
import com.gbs.flash.utils.factory.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Api(value = "商品属性键管理", tags = "商品订单管理")
@RestController
@RequestMapping("/shop/goods/attr/key")
public class AttrKeyController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private AttrKeyService attrKeyService;

    @ApiOperation("查询所有商品属性键")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Object list() {
        Page<AttrKey> page = new PageFactory<AttrKey>().defaultPage();
        page = attrKeyService.queryPage(page);
        return Rets.success(page);
    }

    @ApiOperation("编辑商品属性名")
    @RequestMapping(method = RequestMethod.POST)
    @BussinessLog(value = "编辑商品属性名", key = "name")
    public Object save(@ModelAttribute AttrKey tShopGoodsAttrKey) {
        if (tShopGoodsAttrKey.getId() == null) {
            attrKeyService.insert(tShopGoodsAttrKey);
        } else {
            attrKeyService.update(tShopGoodsAttrKey);
        }
        return Rets.success();
    }

    @ApiOperation("删除商品属性名")
    @RequestMapping(method = RequestMethod.DELETE)
    @BussinessLog(value = "删除商品属性名", key = "id")
    public Object remove(Long id) {
        if (StringUtil.isEmpty(id)) {
            throw new ApplicationException(ApplicationExceptionEnum.REQUEST_NULL);
        }
        AttrKey attrKey = attrKeyService.get(id);
        if (!attrKey.getAttrVals().isEmpty()) {
            throw new ApplicationException(ApplicationExceptionEnum.DATA_CANNOT_REMOVE);
        }
        attrKeyService.deleteById(id);
        return Rets.success();
    }

    @ApiOperation("修改商品属性名")
    @RequestMapping(value = "updateAttrName", method = RequestMethod.POST)
    @BussinessLog(value = "修改商品属性名", key = "id")
    public Object updateAttrName(@RequestParam("id") Long id, @RequestParam("attrName") String attrName) {
        if (StringUtil.isEmpty(id)) {
            throw new ApplicationException(ApplicationExceptionEnum.REQUEST_NULL);
        }
        AttrKey attrKey = attrKeyService.get(id);
        attrKey.setAttrName(attrName);
        attrKeyService.update(attrKey);
        return Rets.success();
    }
}
